package com.pilipala.handler;

import com.pilipala.constant.MessageConstant;
import com.pilipala.exception.BaseException;
import com.pilipala.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理业务异常信息
     * @param exception 异常类
     * @return 返回结果类
     */
    @ExceptionHandler
    public Result<?> exceptionHandler(BaseException exception){
        log.error("出现异常！！{}",exception.getMessage());
        return Result.error(exception.getMessage());
    }

    @ExceptionHandler
    public Result<?> sqlExceptionHandler(SQLIntegrityConstraintViolationException exception){
        String message = exception.getMessage();
        //如果是唯一性矛盾
        if (message.contains("Duplicate entry")){
            String[] strings = message.split(" ");
            String userName =strings[2];
            String msg =userName + MessageConstant.ALREADY_EXIT;
            return Result.error(msg);
        }
        else{
            //其他的错误就封装在这里面不要给外部看了
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}
